import json

from common.api_client import PmsApi
from config.env_config import env_config
from utils.logger import logger


class PmsToken:
    @staticmethod
    def get_token_by_url(name="test1174@yingmi.cn", password="123456"):
        data = {"username": name, "password": password}
        resp = PmsApi.noauth_api_login(data)
        token = resp['result']['token']
        return token

    @classmethod
    def create_auth_by_url(cls, name="test1174@yingmi.cn", password="123456", auth_name="admin"):
        """通过接口获取token，创建auth.json"""
        token = cls.get_token_by_url(name=name, password=password)
        cookies = {"cookies": [],
                   "origins": [{"origin": env_config.base_url, "localStorage": [{"name": "token", "value": token}]}]}
        with open(f"{cls.AUTH_DIR}/{auth_name}.json", "w") as file:
            # file.write(json.dumps(cookies))
            json.dump(cookies, file, indent=4)
            logger.info(f"创建{auth_name}.json文件成功")

    @classmethod
    def get_token_by_file(cls, auth_name="admin"):
        """获取存在json文件中的token"""
        file_path = f"{cls.AUTH_DIR}/{auth_name}.json"
        with open(file_path, "r") as file:
            data = json.load(file)["origins"][0]["localStorage"][0]["value"]
            return data